<?php
/* This file is part of Mirasol CMS
   (C) 2013-2014 by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

class Database
{
  private $db;
  private $mysqli;
  private $result;
  
  public $num_rows;

  function __construct ()
  {
    /* Read site.conf */
    if (file_exists ("{$_SERVER['DOCUMENT_ROOT']}/site.conf"))
      {
        $siteconf = simplexml_load_file ("{$_SERVER['DOCUMENT_ROOT']}/site.conf");
        
        $this->db = array ();
        $this->db['server'] = $siteconf->mysql[0]->server;
        $this->db['user'] = $siteconf->mysql[0]->user;
        $this->db['password'] = $siteconf->mysql[0]->password;
        $this->db['dbname'] = $siteconf->mysql[0]->dbname;
        $this->db['tblprefix'] = $siteconf->mysql[0]->tblprefix;
      }
    else
      exit("Failed to open 'site.conf'.");
  }
  
  public function close ()
  {
    if ($this->mysqli) // <- Depricated line
      $this->mysqli->close ();
  }

  public function connect ()
  {
    $this->mysqli = new mysqli ($this->db['server'], $this->db['user'], $this->db['password'], $this->db['dbname']);
    if ($this->mysqli->connect_errno)
      exit ($this->mysqli->connect_error);
    $this->mysqli->set_charset ("utf8");
  }

  public function fetch ()
  {
    return $this->result->fetch_array ();
  }

  public function free ()
  {
    if ($this->result)
      $this->result->free ();
  }

  public function query ($qs, $debug = false)
  {
    $this->result = $this->mysqli->query ($qs);
    
    if (is_object ($this->result))
      $this->num_rows = $this->result->num_rows;
    
    if ($this->result === false && $debug === true)
      print $this->mysqli->error;
    
    return is_object ($this->result) ||  $this->result === true ? true : false;
  }
  
  public function table ($name)
  {
    return $this->db['tblprefix'].$name;
  }

  public function safestring ($s)
  {
    return $this->mysqli->real_escape_string ($s);
  }
}
